package com.tanhua.dubbo.api;

import com.tanhua.domain.db.PageResult;
import com.tanhua.domain.mg.TodayBeautyMG;
import com.tanhua.dubbo.mg.ReCommendApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.ObjectUtils;

import java.util.List;


@Service
public class ReCommendImpl implements ReCommendApi {

    //注入MongoTemplate对象
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 根据用户Id推荐今日佳人
     */
    @Override
    public TodayBeautyMG reCommendById(Long uid) {
        //查询score（缘分值）最高的一位出来
        Query query = new Query(Criteria.where("toUserId")
                .is(uid)).limit(1).with(Sort.by(Sort.Order.desc("score")));
        //将查询的条件传入findOne
        return mongoTemplate.findOne(query, TodayBeautyMG.class);
    }
    /**
     * 推荐朋友
     */
    @Override
    public PageResult<TodayBeautyMG> reCommendsResult(Long currentId, Long page, Long pagesize) {
        //分页查询
        Query query = new Query(Criteria.where("toUserId").is(currentId))
                .limit(pagesize.intValue())
                .skip((page-1)*pagesize);
        //调用mongoTempalate方法
        List<TodayBeautyMG> mgList = mongoTemplate.find(query, TodayBeautyMG.class);
        //当前页 page
        //每页记录 pagesize
        //总记录数
        long count = mongoTemplate.count(query, TodayBeautyMG.class);
        //总页码
        int pages = count / pagesize + count % pagesize == 0 ? 1 : 0;
        //封装返回
        PageResult<TodayBeautyMG> result = new PageResult<TodayBeautyMG>();
        result.setItems(mgList);
        result.setCounts((int)count);
        result.setPage(page.intValue());
        result.setPagesize(pagesize.intValue());
        result.setPages(pages);
        return result;
    }

    /**
     * 根据当前用户id 和佳人id 查询匹配记录
     * @param currentUserId
     * @param BeautyGirlId
     * @return
     */
    @Override
    public TodayBeautyMG findTodayBeautyMGByTwoId(Long currentUserId, Long BeautyGirlId) {
        Query query = new Query();
        //userId：佳人的id
        //toUserId ：当前用户Id
        query.addCriteria(Criteria.where("userId")
                .is(BeautyGirlId)
                .and("toUserId")
                .is(currentUserId));
        TodayBeautyMG todayBeautyMG = mongoTemplate.findOne(query, TodayBeautyMG.class);
        //如果todayBeautyMG对象为null 那么就给它加一个
        if(ObjectUtils.isEmpty(todayBeautyMG)){
            todayBeautyMG = new TodayBeautyMG();
            todayBeautyMG.setScore(97.7);
            todayBeautyMG.setUserId(BeautyGirlId);
            todayBeautyMG.setToUserId(currentUserId);
        }
        return todayBeautyMG;
    }
}
